import {
    login,
    getUserInfo,
    getMoveRouter
} from "@/api/index";
import {
    getToken,
    setToken,
    removeToken,
    setUser,
    getUser,
    removeUser
} from '@/utils/auth'
import {
    resetRouter
} from '@/router'
// import routerLsit from '@/utils/getMoveRouter.json'
// import roleRouter from '@/utils/roleRouter.json'
// import arrayToTree from "array-to-tree";

const getDefaultState = () => {
    return {
        token: getToken(),
        name: '',
        avatar: '',
        menus: "", //存放路由表的容器
        username: ''
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_MENU: (state, menus) => {
        state.menus = menus
    },
    GETUSERNAME(state, username) {
        state.username = username
    }
}

const actions = {
    // user login
    login({
        commit
    }, userInfo) {
        const {
            username,
            password
        } = userInfo
        return new Promise((resolve, reject) => {
            login({
                username: username.trim(),
                password: password
            }).then(response => {
                const res = response.data
                commit('SET_TOKEN', res.accessToken)
                setToken(res.accessToken)
                sessionStorage.setItem('Admin-Token', res.accessToken);
                sessionStorage.setItem('userId', res.userId); //存储用户id
                sessionStorage.setItem('tenantId', res.tenantId); //存储租户id
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // get user info
    getInfo({
        commit,
        state
    }) {
        return new Promise((resolve, reject) => {
            getUserInfo({
                permission: true
            }).then(response => {
                let res = response.data;
                sessionStorage.setItem('userInfo', JSON.stringify(res));
                sessionStorage.setItem('deptId', res.deptId); //存储部门id
                const data = {
                    name: res.name,
                    photo: res.photo
                }
                if (!data) {
                    return reject('验证失败, 请重新登录.')
                }
                const {
                    name,
                    photo
                } = data //从data中解构出name 和头像 
                commit('SET_NAME', name) //把name 保存到vuex中
                commit('SET_AVATAR', photo) //把头像保存到vuex中
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    // getRouter
    getRouter({
        commit,
        state
    }) {
        return new Promise((resolve, reject) => {
            let morenRole = JSON.parse(sessionStorage.getItem('userInfo')).roles[0]
            let userNmae = JSON.parse(sessionStorage.getItem('userInfo'))
            commit('GETUSERNAME', userNmae.username)
            let path = sessionStorage.getItem('roleCode')
            if (path) {
                morenRole = sessionStorage.getItem('roleCode')
            } else {
                sessionStorage.setItem('roleCode', morenRole)
            }
            getMoveRouter({
                group: "web",
                roleCode: morenRole
            }).then(response => {
                // let path = sessionStorage.getItem('roleCode')
                // let arr1 = [] //当前角色的-路由列表
                // let arr2 = response.data  //平台所有角色的-路由列表
                // let arr3 = []  //切换到当前角色-已过滤的-路由列表
                // let menus = [] //树形结构-数据
                // let morenRole = JSON.parse(sessionStorage.getItem('userInfo')).roles[0]
                // //切换角色-改变路由列表
                // if(path){
                //   roleRouter.data.forEach(obj => {
                //     if(obj.roleCode == path){
                //       arr1 = obj.royterList
                //     }
                //   });
                //   arr3 = arr2.filter(item=> arr1.indexOf(item.path) > -1)
                //   menus = arrayToTree(arr3, {
                //     parentProperty: 'parentId',
                //     customID: 'id'
                //   });
                // }else{ //默认登陆-获取路由
                //   sessionStorage.setItem('roleCode',morenRole)
                //   roleRouter.data.forEach(obj => {
                //     if(obj.roleCode == morenRole){
                //       arr1 = obj.royterList
                //     }
                //   });
                //   arr3 = arr2.filter(item=> arr1.indexOf(item.path) > -1)
                //   menus = arrayToTree(arr3, {
                //     parentProperty: 'parentId',
                //     customID: 'id'
                //   });
                // }
                const menus = response.data
                    //如果需要404 页面，请在此处添加 
                menus.push({
                        path: "/404",
                        component: "404",
                        hidden: true
                    }, {
                        path: "*",
                        redirect: "/404",
                        hidden: true
                    })
                    // console.log(menus,'路由列表');
                commit('SET_MENU', menus) //把name 保存到vuex中
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    // user logout
    logout({
        commit,
        state,
        dispatch
    }) {
        return new Promise((resolve, reject) => {
            commit('SET_TOKEN', '')
            commit('RESET_STATE')
            removeToken()
            resetRouter()
            dispatch('tagsView/delAllViews', null, {
                root: true
            })
            sessionStorage.clear()
            resolve()
        })
    },

    // remove token
    resetToken({
        commit
    }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first //清楚token
            commit('RESET_STATE')
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}